package net;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TCPServer {

    //服务Socket需要绑定的端口号
    private static final int PORT = 4090;
    //本地文件目录要展示的根路径
    private static final String BASE_PATH = "E:/";

    private static ServerSocket listenSocket = null;

    public TCPServer(int port) throws IOException {
        listenSocket = new ServerSocket(port);
        System.out.println();
    }

    public static void main(String[] args) throws IOException {
        TCPServer tcpServer = new TCPServer(PORT);
        tcpServer.start();
    }

    private void start() throws IOException{
        System.out.println("服务器启动！");
        System.out.println("等待连接客户端..");
        ExecutorService executorService = Executors.newCachedThreadPool();

        while (true) {
            executorService.submit(() -> {
                try {
                    Socket socket = listenSocket.accept();
                    processConnection(socket);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
        }
        //阻塞等待连接
    }

    private void processConnection(Socket client) throws IOException{
        System.out.println("[" + client.getPort() + "/" +
                client.getInetAddress().getHostAddress() +
                "]成功创建与客户端的连接！");
        try (InputStream is = client.getInputStream();
             OutputStream os = client.getOutputStream()) {
            while (true) {
                //对client Socket里的数据进行读取
                Scanner scanner = new Scanner(is);
                while (scanner.hasNext()) {
                    String s = scanner.next();
                    System.out.println("客户端输入：" + s);
                    String response = process(s);
                    PrintWriter pw = new PrintWriter(os);
                    pw.write(response);
                    pw.flush();
                }
                System.out.println("[" +
                        client.getPort() + "/" +
                        client.getInetAddress().getHostAddress() +
                        "]客户端下线");
                break;
            }
        } finally {
            client.close();
        }
    }

    private static String process(String request) {
        return request;
    }

    public static void main1(String[] args) throws IOException{
        ServerSocket server = new ServerSocket(PORT);

        System.out.println("小飞棍来喽");
        while (true) {
            System.out.println("----------------");
            System.out.println("等待与客户端建立TCP连接...");

            Socket client = server.accept();
            System.out.printf("客户端IP：%s\n", client.getInetAddress().getHostAddress());
            System.out.printf("客户端端口号：%s\n", client.getPort());

            InputStream is = client.getInputStream();
            BufferedReader bf = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String request = bf.readLine();

            System.out.println("客户端请求的文件列表路径名为:" + BASE_PATH + request);
            File dir = new File(BASE_PATH + request);
            File[] children = dir.listFiles();
            
            OutputStream os = client.getOutputStream();
            PrintWriter pw = new PrintWriter(new OutputStreamWriter(os, "UTF-8"));
            if (children != null) {
                for (File f: children) {
                    pw.println(f.getName());
                }
            }
            pw.flush();
            server.close();
        }
    }

    public static void main0(String[] args) throws IOException {
        ServerSocket server = new ServerSocket(PORT);

        while (true) {
            System.out.println("------------------");
            System.out.println("等待客户端与服务器构建连接...");

            //ServerSocket调用accept方法后开始尝试从对应端口接收数据，接收到的数据用一个Socket接收
            Socket client = server.accept();

            //InetAddress == 套接字所连接的地址
            //HostAddress == IP
            System.out.printf("客户端IP: %s\n", client.getInetAddress().getHostAddress());
            System.out.printf("客户端端口号: %s\n", client.getPort());

            System.out.println("收到客户端请求：");

            //从Socket输入流中获取客户端的数据
            InputStream is = client.getInputStream();
            //将字节流包装为字符流，方便获取字符串内容？
            BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String line = new String();

            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
            client.close();
        }
    }

}
